/*
 * Bunisoft the Open Source Communications Company
 * Copyright 2006, Bunisoft Inc.,
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.teremail.panto;

import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

/**
 * Implementation of a mime parser that uses a boundary stream
 * to demarcate the limits of each mime part.  Instances of this
 * class are NOT thread safe.
 * 
 * @author Michael Barker
 *
 */
public class MimeParser {

    private final static int SIZE = 8192;
    private final static byte[] ENDL = { '\r', '\n' };

    private int size = SIZE;
    private int pbSize = SIZE + 100;
    private ContentHandler handler = new NullContentHandler();
    private HeaderParser hp = new HeaderParser();

    public void parse(InputStream in) throws IOException {
        PushbackInputStream pIn = new PushbackInputStream(in, pbSize);
        parseMessage(pIn);
    }
    
    public void setContentHandler(ContentHandler handler) {
        this.handler = handler;
    }

    public void setBufferSize(int size) {
        this.size = size;
    }

    /**
     * Parses a message, this is top level and can be called by parts that
     * contain messages also.
     * 
     * @param in
     * @throws IOException
     * @throws ParseException
     */
    private void parseMessage(PushbackInputStream in) throws IOException {
        
        handler.startMessage();
        BodyHeader header = hp.parseHeader(handler, in, new ContentType());
        parseBodyPart(in, header);
        handler.endMessage();
    }
    
    /**
     * Parses a multipart body handles preamble all of the parts and
     * the epilogue.
     * 
     * @param in
     * @param header
     * @throws IOException
     * @throws ParseException
     */
    private void parseMultipart(PushbackInputStream in, BodyHeader header) 
            throws IOException {
        
        byte[] pattern = header.getContentType().getPattern(false);
        handler.startMultipart(header);
        parsePreamble(in, pattern);
        
        byte[] patternNL = header.getContentType().getPattern(true);
        boolean finished = false;
        do {
            BoundaryInputStream bIn = new BoundaryInputStream(in, patternNL, size);
            PushbackInputStream pIn = new PushbackInputStream(bIn, pbSize);
            // Remove the new line and white space that trails the pattern.
            consumeEOF(pIn);
            // Parse the mime body part.
            parseMimeBodyPart(pIn, header.getContentType().getDefault());
            int b1 = in.read();
            int b2 = in.read();

            finished = b1 == -1 || b2 == -1 || ((b1 == '-') && (b2 == '-'));
            
            if (!finished) {
                in.unread(b2);
                in.unread(b1);
            }
            
        } while (!finished);
        
        consumeEOF(in);
        parseEpilogue(in);
        handler.endMultipart();
    }
    
    /**
     * Parses the bodypart, the content header is supplied.
     * 
     * @param in
     * @param header
     * @throws IOException
     * @throws ParseException
     */
    public void parseBodyPart(PushbackInputStream in, BodyHeader header) 
            throws IOException {
        if (header.getContentType().isMulitpart()) {
            parseMultipart(in, header);
        } else if (header.getContentType().isMessage()) {
            parseMessage(in);
        } else {
            handler.body(header, in);
        }
    }
    
    /**
     * Parses a mime body part, will first parse the content header of the
     * parse then do the appropriate parsing action.
     * 
     * @param pIn
     * @param defaultContentType The default content type for this message.
     * @throws IOException
     * @throws ParseException
     */
    private void parseMimeBodyPart(PushbackInputStream pIn, 
            ContentType defaultContentType) throws IOException {

        handler.startBodyPart();
        BodyHeader header = hp.parseHeader(handler, pIn, defaultContentType);
        parseBodyPart(pIn, header);
        handler.endBodyPart();
    }

    private void parsePreamble(PushbackInputStream in, byte[] pattern)
            throws IOException {
        InputStream bIn = new BoundaryInputStream(in, pattern, ENDL, size);
        handler.preamble(bIn);
    }

    private void parseEpilogue(PushbackInputStream in) throws IOException {
        handler.epilogue(in);
    }

    private void consumeEOF(PushbackInputStream in) throws IOException {
        IOUtil.appendLine(new StringBuilder(), in, "US-ASCII");
    }
}
